from django.core.validators import RegexValidator

from tools.datetime import yesterday
from django.db import models
from django.contrib.postgres.fields import ArrayField
# Create your models here.


class AppVisitCount(models.Model):
    """应用访问量统计"""
    resource = models.CharField(max_length=100, unique=True)            # 应用(资源)名称
    count = models.IntegerField(default=0)                              # 应用访问量
    last_update = models.DateTimeField()                                # 统计截止时间


# 基本作废
class DeviceInfo(models.Model):
    """设备信息表"""
    model = models.CharField(max_length=50)                     # 设备型号
    os_version = models.CharField(max_length=50)                # 系统版本
    imei = models.CharField(max_length=17)                      # IMEI
    device_uuid = models.CharField(max_length=50, null=True, unique=True)    # DEVICE_UUID
    mac_addr = models.CharField(max_length=17, null=True)       # MAC地址
    object_id = models.CharField(max_length=24, unique=True)    # MongoDB ObjectId
    app = models.PositiveIntegerField(default=0)                # 安装应用总数
    danger_app = models.PositiveIntegerField(default=0)         # 恶意应用数
    risk_app = models.PositiveIntegerField(default=0)           # 风险应用数
    sensitive_app = models.PositiveIntegerField(default=0)      # 敏感应用数
    is_secure = models.BooleanField()                           # 设备是否安全
    is_root = models.BooleanField()                             # 设备是否root
    security_description = models.TextField(                    # 风险描述
        null=True, blank=True
    )
    user = models.ForeignKey(
        'zmad.ZTPUser',
        to_field='username',
        db_column='username',
        on_delete=models.CASCADE,
        db_constraint=False,  # Django不会实际添加ON DELETE CASCADE到外键约束，我们需要手动创建
        related_name='old_devices'
    )
    date = models.DateField(default=yesterday)                  # 记录日期


class ResourceSensLevel(models.Model):
    sen_level = models.SmallIntegerField(default=0)      # 应用标记，用于标记应的敏感等级，1为低，2为中，3为高，0为无
    resource = models.OneToOneField(
        'zmad.ZTPResource',
        to_field='name',
        db_column='name',
        on_delete=models.CASCADE,
        db_constraint=False,  # Django不会实际添加ON DELETE CASCADE到外键约束，我们需要手动创建
        related_name='sen_level'
    )


# 入网设备管控
class Device(models.Model):

    DEVICE_TYPE_CHOICE = (
        (1, "手机"),
        (2, "平板"),
        (3, "台式机"),
        (4, "笔记本"),
        (5, "其他")
    )
    BELONG_CHOICE = (
        (1, "配发"),
        (2, "个人"),
        (3, "其他")
    )
    PLATFORM_CHOICE = (
        (1, "android"),
        (2, "windows"),
        (4, 'linux')
    )
    STRATEGY_CHANNELS = (
        (0, '不区分渠道'),
        (1, 'app'),
        (2, '客户端'),
        (3, 'web'),
    )

    IP = models.CharField(max_length=1024, default="", null=True, blank=True)  # "10.10.10.10, 10.10.10.11,"
    mac = models.CharField(max_length=64, default="", null=True, blank=True)   # 主板sn码
    version = models.CharField(max_length=128, default="", null=True, blank=True)  # 系统版本
    production = models.CharField(max_length=128, default="", null=True, blank=True)   # 厂商
    device_uuid = models.CharField(max_length=128, default="", unique=True)  # 设备唯一编码
    name = models.CharField(max_length=128, default="")     # 设备名称
    device_name = models.CharField(max_length=128, default="")     # 设备资产名称
    model = models.CharField(max_length=128, default="", null=True, blank=True)    # 设备型号
    os_version = models.CharField(max_length=128, default="", null=True, blank=True)   # 系统版本
    # imei = models.CharField(max_length=17, default="", null=True, blank=True)  # imei码
    # imsi = models.CharField(max_length=32, default="", null=True, blank=True)  # IMSI
    mac_addr = models.CharField(max_length=1024, default="", blank=True)    # mac地址, 以逗号隔开
    antiy_active = models.BooleanField(default=False)   # 智甲激活.默认不激活
    user = models.ForeignKey(  # 允许一对多.关联zmad.ztp_user 表 主键ID,设备注册用户
        'zmad.ZTPUser',
        on_delete=models.SET_NULL,
        null=True,
        related_name='devices',
    )
    device_type = models.IntegerField(default=5, choices=DEVICE_TYPE_CHOICE, null=True)    # 设备类型
    device_type_str = models.CharField(max_length=8, default="", null=True)    # 设备类型文字表示
    online = models.BooleanField(default=True, null=True)  # 是否在线
    last_login = models.DateTimeField()    # 上次登录时间
    # belong = models.IntegerField(default=3, choices=BELONG_CHOICE, null=True)     # 设备归属
    # safety = models.CharField(max_length=128, default="", null=True, blank=True)   # 安全域
    platform = models.IntegerField(default=1, choices=PLATFORM_CHOICE, null=True)  # 平台
    # uuid = models.CharField(max_length=64, default="", null=True, blank=True)   # 主板sn码(以mac为优先级)
    # code = models.CharField(max_length=64, default="", null=True, blank=True)  # 资产编码
    # uninstalled = models.BooleanField(default=False, null=True)    # 是否卸载
    # group = models.IntegerField(null=True)   # 关联auth_group 主键ID
    # group = models.OneToOneField(
    #     'app_user.ZTPGroup',
    #     on_delete=models.SET_NULL,
    #     null=True,
    #     related_name='relative_devices',
    # )
    # created_time = models.DateTimeField(auto_now_add=True)  # 创建时间
    # updated_time = models.DateTimeField(auto_now=True)  # 更新时间
    last_user_id = models.IntegerField(null=True)   # 最近登录用户
    # ping_time = models.DateTimeField(null=True, auto_now_add=True)     # 心跳时间
    risk_list = ArrayField(models.CharField(max_length=64), default=[], null=True, blank=True)  # 触发风险策略
    is_secure = models.BooleanField(default=True, null=True)   # 设备是否安全，基于是否触发了策略来判断
    # nic = models.CharField(max_length=256, default="", null=True)    # 网卡名称
    # cpu_type = models.CharField(max_length=256, default="", null=True)    # CPU 型号
    # cpu_number = models.CharField(max_length=64, default="", null=True)    # CPU 物理数量
    # ipv6 = models.CharField(max_length=256, default="", null=True)      # ipv6地址
    # core_version = models.CharField(max_length=64, default="", null=True)    # 系统内核版本
    # cpu_arch = models.CharField(max_length=64, default="", null=True)    # 系统架构
    # cpu_frequency = models.CharField(max_length=64, default="", null=True)    # CPU 频率

    class Meta:
        managed = False
        db_table = '"zmad"."device"'

    def check_device_online(self):
        # _value = redis.get(self.device_uuid)
        # if _value == '1':
        #     self.online = True
        # else:
        #     self.online = False
        # self.save()
        return self.online


class ZTPGroup(models.Model):
    """组织架构表"""
    name = models.CharField(                                            # 组织名称
        max_length=100,
        error_messages={
            'null': '组织名称不能为空。',
            'blank': '组织名称不能为空。',
            'invalid': '请输入一个合法的组织名称。',
            'unique': '当前分支中已存在同名的组织。',
        },
        validators=[
            RegexValidator(r'[#]', message='组织名称不能含有#等字符。', inverse_match=True)
        ]
    )

    class Meta:
        managed = False
        db_table = '"zmad"."app_user_ztpgroup"'
